import 'dart:io';
import 'package:oktoast/oktoast.dart';
import 'package:path/path.dart' as path;
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:sj001/request/request.dart';
import '../../model/inputMessage.dart';
import '../../utils/Utils.dart';


class SelectFilePage extends StatefulWidget {
  SelectFilePage({this.callback,Key? key}) : super(key: key);
  Function(InputMessageFileData)? callback;
  @override
  State<SelectFilePage> createState() => _SelectFilePageState();
}

class _SelectFilePageState extends State<SelectFilePage> {
  List<Map<String, dynamic>> items = [
    // {
    //   'title': '选择文件',
    //   'type': 1,
    // },
    {
      'title': '选择图片',
      'type': 2,
    },
    // {
    //   'title': '拍照',
    //   'type': 3,
    // },
  ];

  onSelect(int type) {
    if (type == 1) {
      onSelectFile();
    } else if (type == 2) {
      onSelectPhoto();
    } else if (type == 3) {
      onTakePhoto();
    }
  }

  onSelectFile() {
    FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowedExtensions: ['xls', 'xlsx', 'pdf', 'doc', 'docx', 'txt'],
    ).then((result) {
      if (result != null) {
        PlatformFile file = result.files.single;
        InputMessageFileData data = InputMessageFileData(2,path: file.path,name: file.name,size: file.size);
        handleData(data);
      }
    });
  }

  onSelectPhoto() {
    ImagePicker picker = ImagePicker();
    picker.pickImage(source: ImageSource.gallery).then((value) {
      if (value != null) {
        File file = File(value.path);
        String fileName = path.basename(file.path);
        InputMessageFileData data = InputMessageFileData(1,path: file.path,name: fileName,size: file.lengthSync());
        handleData(data);

      }
    });
  }

  onTakePhoto() {
    ImagePicker picker = ImagePicker();
    picker.pickImage(source: ImageSource.camera).then((value) {
      if (value != null) {
        File file = File(value.path);
        String fileName = path.basename(file.path);
        InputMessageFileData data = InputMessageFileData(1,path: file.path,name: fileName,size: file.lengthSync());
        handleData(data);
      }
    });
  }

  handleData(InputMessageFileData data){
    print(data.toJson());
    double size = (data.size??0) / (1024*1024);
    if (size > 20){
      showToast('请选择小于20M的文件嚯图片');
      return;
    }
    CustomRequest.uploadFile(filePath: data.path??'');
    // widget.callback?.call(data);
    // Get.back();
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(color: Colors.white),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            const Icon(
              Icons.file_copy_sharp,
              size: 150,
            ),
            const SizedBox(height: 20),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  '${Utils.appName}可以解析、总结、回答多个文件',
                  style: const TextStyle(
                    color: Colors.black,
                    fontWeight: FontWeight.w600,
                    fontSize: 18,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 10),
            const Padding(
              padding: EdgeInsets.symmetric(horizontal: 30),
              child: Text(
                '支持PDF、文档、表格、图片等格式，最多上传10个文件，每个文件不超过20M',
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: Color(0xff666666),
                  fontSize: 16,
                ),
              ),
            ),
            const SizedBox(height: 20),
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 50),
              child: ListView.builder(
                shrinkWrap: true,
                itemBuilder: (ctx, index) {
                  Map<String, dynamic> item = items[index];
                  return InkWell(
                    onTap: () => onSelect(item['type'] ?? 0),
                    child: Container(
                      height: 44,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(22),
                        color: const Color(0x80aaaaaa),
                      ),
                      margin: EdgeInsets.only(
                          bottom: index == items.length - 1 ? 0 : 15),
                      alignment: Alignment.center,
                      child: Text(
                        item['title'] ?? '',
                        style: const TextStyle(
                          color: Colors.black,
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                  );
                },
                itemCount: items.length,
              ),
            ),
            const SizedBox(height: 50),
            InkWell(
              onTap: () => Get.back(),
              child: Container(
                padding: const EdgeInsets.all(5),
                decoration: BoxDecoration(
                    border: Border.all(
                      color: Colors.black,
                      width: 0.5,
                    ),
                    borderRadius: BorderRadius.circular(20)),
                child: const Icon(
                  Icons.close_rounded,
                  size: 30,
                  color: Colors.black,
                ),
              ),
            ),
            const SizedBox(height: 40),
          ],
        ),
      ),
    );
  }
}
